import Axios from "axios";
import Vue from "vue";
import { Notify } from "quasar";
import qs from "qs";

/**
 * axios initialization
 */
const axios = Axios.create({
  baseURL: Vue.prototype.$baseURL,
  timeout: Vue.prototype.$timeOut
});

axios.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem("access_token");
    config.headers.imprint = token;
    if (config.type) {
      switch (config.type) {
        case "FORM-DATA":
          config.transformRequest = [
            data => {
              return "args=" + JSON.stringify(data);
            }
          ];
          break;
        case "FORM":
          config.headers["Content-Type"] = "application/x-www-form-urlencoded";
          config.data = qs.stringify(config.data);
          break;
        default:
          break;
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response.data.code !== 0) {
      Notify.create({
        message: response.data.msg,
        color: "red",
        icon: "error"
      });
      return Promise.reject(response.data.msg);
    }
    return response.data.data;
  },
  error => {
    const defaultNotify = {
      message: "未知错误",
      icon: "warning",
      color: "warning",
      position: "top",
      timeout: 1500
    };
    if (
      error.code === "ECONNABORTED" ||
      error.message.indexOf("timeout") !== -1 ||
      error.message === "Network Error"
    ) {
      defaultNotify.message = "网络异常";
      Notify.create(defaultNotify);
      return Promise.reject(error);
    }
    switch (error.response.status) {
      case 403:
        defaultNotify.message = "拒绝访问(403)";
        break;
      case 404:
        defaultNotify.message = "资源不存在(404)";
        break;
      case 408:
        defaultNotify.message = "请求超时(404)";
        break;
      case 500:
        defaultNotify.message = "服务器错误(500)";
        break;
      case 501:
        defaultNotify.message = "服务未实现(501)";
        break;
      case 502:
        defaultNotify.message = "网络错误(502)";
        break;
      case 503:
        defaultNotify.message = "服务不可用(503)";
        break;
      case 504:
        defaultNotify.message = "网络超时(504)";
        break;
      case 505:
        defaultNotify.message = "HTTP版本不受支持(505)";
    }
    Notify.create(defaultNotify);
    return Promise.reject(error);
  }
);

export default axios;
